<template>
  <div class="pdf-preview-page">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <p>正在加载PDF图片...</p>
      </div>
    </div>
    <!-- PDF图片查看器 -->
    <PdfImageViewer
        v-else
        :imageUrls="imageUrls"
        :totalPages="totalPages"
        :coverData="coverData"
        :tableOfContents="tableOfContents"
        :materialPageCounts="materialPageCounts"
        @generatePdf="handleGeneratePdf"
        @editCover="handleEditCover"
        @goBack="handleGoBack"
        style="margin-top: 30px;"
    />
    <!-- 封面编辑器弹窗 -->
    <CoverEditor
        v-if="showCoverEditor"
        :visible="showCoverEditor"
        :initialCoverData="coverData"
        @update:visible="showCoverEditor = $event"
        @confirm="handleCoverEditorConfirm"
        @cancel="handleCoverEditorCancel"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import PdfImageViewer from '@/components/academic/PdfImageViewer.vue'
import CoverEditor from '@/components/CoverEditor.vue'
import { getPdfImages } from '@/api/Assistants/material.js'
import { jsPDF } from 'jspdf'

const router = useRouter()
const route = useRoute()

// 响应式数据
const isLoading = ref(true)
const imageUrls = ref([])
const totalPages = ref(0)
const showCoverEditor = ref(false)
const materialPageCounts = ref([])

// 从路由参数获取项目信息
const projectInfo = ref({
  projectName: route.query.projectName || '',
  projectLevel: route.query.projectLevel || '',
  projectNumber: route.query.projectNumber || '',
  startTime: route.query.startTime || '',
  projectStatus: route.query.projectStatus || '',
  results: JSON.parse(route.query.results || '[]')
})

// 封面数据 (更新结构以匹配 CoverEditor 的输出)
const coverData = ref({
  contentItems: [], // 存储标题、副标题等动态内容
  font: 'SimHei, 黑体', // 默认字体
  declarationInfo: {
    person: '',
    unit: '',
    position: { y: 400 }, // 申报信息的位置
    labels: {
      person: '申报人',
      unit: '申报单位'
    }
  }
})

// 目录数据
const tableOfContents = ref([])

// 获取字体大小的辅助函数 (与 CoverEditor 和 PdfImageViewer 保持一致)
const getFontSize = (type) => {
  switch (type) {
    case 'h1': return '32px'
    case 'h2': return '24px'
    case 'h3': return '20px'
    default: return '16px'
  }
}

// 初始化数据
const initData = () => {
  // 初始化 coverData.contentItems
  coverData.value.contentItems = [
    {
      id: Date.now(),
      type: 'h1',
      text: '附件材料',
      position: { y: 100 }
    },
    {
      id: Date.now() + 1,
      type: 'h2',
      text: projectInfo.value.projectName || '',
      position: { y: 180 }
    }
  ];

  // 初始化 coverData.declarationInfo 的位置
  coverData.value.declarationInfo.position.y = 400;

  // 生成目录数据（不包含页码，页码将在组件中计算）
  if (projectInfo.value.results && projectInfo.value.results.length > 0) {
    tableOfContents.value = projectInfo.value.results.map((item, index) => ({
      title: `${item.type}: ${item.title}`,
      originalIndex: index // 保存原始索引，用于页码计算
    }))
  }
}

// 加载所有图片
const loadAllImages = async () => {
  try {
    isLoading.value = true
    const allImageUrls = []
    const pageCounts = []
    for (const result of projectInfo.value.results) {
      if (result.pdfUrl) {
        console.log(`正在加载: ${result.title}`)
        try {
          const response = await getPdfImages(result.pdfUrl)
          console.log(`${result.title} 响应:`, response)
          if (response.code === "0" && response.data.imageUrls) {
            allImageUrls.push(...response.data.imageUrls)
            pageCounts.push(response.data.pageCount || response.data.imageUrls.length)
            console.log(`${result.title} 加载成功，页数: ${response.data.pageCount || response.data.imageUrls.length}`)
          } else {
            pageCounts.push(0)
            console.warn(`${result.title} 加载失败`)
          }
        } catch (error) {
          console.error(`加载 ${result.title} 的图片失败:`, error)
          ElMessage.warning(`${result.title} 的图片加载失败`)
          pageCounts.push(0)
        }
      } else {
        pageCounts.push(0)
      }
    }
    imageUrls.value = allImageUrls
    totalPages.value = allImageUrls.length
    materialPageCounts.value = pageCounts
    console.log('材料页数信息:', pageCounts)
    console.log('总图片数:', allImageUrls.length)
    if (allImageUrls.length === 0) {
      ElMessage.warning('没有找到可显示的图片')
    }
  } catch (error) {
    console.error('加载图片失败:', error)
    ElMessage.error('加载PDF图片失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 生成PDF
const handleGeneratePdf = async () => {
  if (imageUrls.value.length === 0) {
    ElMessage.warning('没有可生成的内容');
    return;
  }
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在生成PDF...',
    background: 'rgba(255, 255, 255, 0.7)',
  });
  try {
    const doc = new jsPDF('p', 'mm', 'a4'); // Portrait, millimeters, A4 size
    const pageWidth = doc.internal.pageSize.getWidth();
    const pageHeight = doc.internal.pageSize.getHeight();
    const margin = 20; // mm

    // --- 生成封面页 ---
    doc.addPage();

    // 创建一个临时 canvas 来绘制封面内容
    const coverCanvas = document.createElement('canvas');
    // 为了更好的清晰度，可以设置更高的分辨率，例如 A4 尺寸的 3 倍 DPI (210mm * 300dpi/25.4mm/inch = 2480px)
    const DPI_SCALE = 3; // 3倍分辨率
    // A4 尺寸 (210mm x 297mm) 转换为像素 (假设 96 DPI 为基准，然后乘以 DPI_SCALE)
    const A4_WIDTH_PX = (210 / 25.4) * 96 * DPI_SCALE;
    const A4_HEIGHT_PX = (297 / 25.4) * 96 * DPI_SCALE;

    coverCanvas.width = A4_WIDTH_PX;
    coverCanvas.height = A4_HEIGHT_PX;
    const ctx = coverCanvas.getContext('2d');

    // 绘制白色背景
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, coverCanvas.width, coverCanvas.height);

    // 确保字体加载 (对于 canvas 绘制中文很重要)
    // 注意：这里假设 '黑体' 和 '宋体' 在用户浏览器环境中可用。
    // 如果需要更可靠的中文支持，需要使用 jsPDF 的 addFont 方法嵌入字体文件。
    // 但对于 canvas 绘制，只要浏览器支持，就可以直接使用。
    await document.fonts.load(`16px ${coverData.value.font}`); // 预加载一个基础字体大小

    // 绘制动态内容项
    coverData.value.contentItems.forEach(item => {
      const fontSizePx = parseFloat(getFontSize(item.type)) * DPI_SCALE; // 字体大小也按比例缩放
      ctx.font = `${fontSizePx}px ${coverData.value.font}`;
      ctx.textAlign = 'center';
      ctx.fillStyle = 'black';
      // 将 item.position.y 从 mm 转换为 canvas 像素坐标
      // 这里的 pageHeight 是 jsPDF 的页面高度 (mm)，A4_HEIGHT_PX 是 canvas 的像素高度
      const yPx = (item.position.y / pageHeight) * A4_HEIGHT_PX;
      ctx.fillText(item.text, coverCanvas.width / 2, yPx);
    });

    // --- 绘制申报信息 ---
    if (coverData.value.declarationInfo && coverData.value.declarationInfo.person !== '' && coverData.value.declarationInfo.unit !== '') {
      const declarationInfo = coverData.value.declarationInfo;
      const fontSizePx = parseFloat(getFontSize('text')) * DPI_SCALE;
      ctx.font = `${fontSizePx}px ${coverData.value.font}`;
      ctx.fillStyle = 'black';
      ctx.textBaseline = 'middle'; // 垂直居中对齐

      // 定义基于 PdfImageViewer.vue CSS 的尺寸和间距
      const VIEWER_WIDTH_PX = 595; // PdfImageViewer .page-container width
      const DECLARATION_BLOCK_WIDTH_VIEWER_PX = 300; // PdfImageViewer .declaration-info width
      const LABEL_WIDTH_VIEWER_PX = 100; // PdfImageViewer .declaration-label width
      const GAP_VIEWER_PX = 15; // PdfImageViewer .declaration-row gap
      const FIXED_VALUE_INPUT_WIDTH_VIEWER_PX = 200; // 关键：固定值输入区域/下划线宽度

      // 将这些像素值按比例缩放到当前 canvas 的像素值
      const declarationBlockWidthPx = (DECLARATION_BLOCK_WIDTH_VIEWER_PX / VIEWER_WIDTH_PX) * A4_WIDTH_PX;
      const labelWidthPx = (LABEL_WIDTH_VIEWER_PX / VIEWER_WIDTH_PX) * A4_WIDTH_PX;
      const gapPx = (GAP_VIEWER_PX / VIEWER_WIDTH_PX) * A4_WIDTH_PX;
      const valueAreaWidthPx = (FIXED_VALUE_INPUT_WIDTH_VIEWER_PX / VIEWER_WIDTH_PX) * A4_WIDTH_PX; // 使用固定宽度

      // 计算申报信息块的起始X坐标，使其在 canvas 上水平居中
      const declarationBlockStartX = (coverCanvas.width / 2) - (declarationBlockWidthPx / 2);

      // 计算值输入区域的起始X坐标
      const valueAreaStartX = declarationBlockStartX + labelWidthPx + gapPx;

      // 计算文本的Y位置 (从 coverData.declarationInfo.position.y)
      const declarationYPx = (declarationInfo.position.y / pageHeight) * A4_HEIGHT_PX;

      // 计算下划线的Y位置 (基于文本中间位置和字体大小)
      const underlineOffsetFromTextMiddle = (fontSizePx / 2) + (2 * DPI_SCALE); // 2px 额外视觉偏移

      // --- 绘制申报人信息 ---
      // 标签部分 (右对齐在其区域内)
      ctx.textAlign = 'right';
      ctx.fillText(
          `${declarationInfo.labels.person}：`,
          declarationBlockStartX + labelWidthPx,
          declarationYPx
      );

      // 申报人值部分 (居中在其区域内)
      ctx.textAlign = 'center';
      const personValueTextX = valueAreaStartX + (valueAreaWidthPx / 2); // 值区域的中心
      ctx.fillText(
          declarationInfo.person,
          personValueTextX,
          declarationYPx
      );

      // 绘制申报人值的下划线
      ctx.beginPath();
      ctx.strokeStyle = 'black';
      ctx.lineWidth = 1 * DPI_SCALE;
      const personUnderlineY = declarationYPx + underlineOffsetFromTextMiddle;
      ctx.moveTo(valueAreaStartX, personUnderlineY); // 下划线起始X
      ctx.lineTo(valueAreaStartX + valueAreaWidthPx, personUnderlineY); // 下划线结束X
      ctx.stroke();

      // --- 绘制申报单位信息 ---
      const nextLineYPx = declarationYPx + fontSizePx * 1.5; // 下一行Y位置

      // 标签部分 (右对齐在其区域内)
      ctx.textAlign = 'right';
      ctx.fillText(
          `${declarationInfo.labels.unit}：`,
          declarationBlockStartX + labelWidthPx,
          nextLineYPx
      );

      // 申报单位值部分 (居中在其区域内)
      ctx.textAlign = 'center';
      const unitValueTextX = valueAreaStartX + (valueAreaWidthPx / 2); // 值区域的中心
      ctx.fillText(
          declarationInfo.unit,
          unitValueTextX,
          nextLineYPx
      );

      // 绘制申报单位值的下划线
      ctx.beginPath();
      ctx.strokeStyle = 'black';
      ctx.lineWidth = 1 * DPI_SCALE;
      const unitUnderlineY = nextLineYPx + underlineOffsetFromTextMiddle;
      ctx.moveTo(valueAreaStartX, unitUnderlineY);
      ctx.lineTo(valueAreaStartX + valueAreaWidthPx, unitUnderlineY);
      ctx.stroke();
    }

    // 将 canvas 内容转换为图片数据 URL
    const imageData = coverCanvas.toDataURL('image/jpeg', 1.0); // 质量1.0
    // 将图片添加到 jsPDF
    doc.addImage(imageData, 'JPEG', 0, 0, pageWidth, pageHeight); // 铺满 A4 页面

    // --- 添加目录页 ---
    doc.addPage();
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(28);
    doc.text('目录', pageWidth / 2, 40, { align: 'center' });

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(14);
    let currentY = 60;
    let currentPdfPage = 3; // Start page number after cover (page 1) and TOC itself (page 2)

    // Calculate actual page numbers for each material
    const materialPageStart = [];
    for (let i = 0; i < materialPageCounts.value.length; i++) {
      materialPageStart.push(currentPdfPage);
      currentPdfPage += materialPageCounts.value[i];
    }

    tableOfContents.value.forEach((item, index) => {
      if (currentY > pageHeight - margin) {
        doc.addPage();
        currentY = margin;
      }
      const pageNumber = materialPageStart[index];
      doc.text(`${item.title}`, margin, currentY);
      doc.text(`${pageNumber}`, pageWidth - margin, currentY, { align: 'right' });
      currentY += 10; // Line height
    });

    // --- 添加图片页面 ---
    const loadImagePromises = imageUrls.value.map((url) => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = () => {
          console.log(`[图片加载成功] URL: ${url}`);
          resolve(img);
        };
        img.onerror = (event) => {
          console.error(`[图片加载失败] URL: ${url}`);
          reject(new Error(`图片加载失败: ${url}`));
        };
        img.src = url;
      });
    });

    const loadedImages = await Promise.all(loadImagePromises);

    loadedImages.forEach((img) => {
      doc.addPage();
      const imgWidth = img.width;
      const imgHeight = img.height;

      const ratio = Math.min(
          (pageWidth - 2 * margin) / imgWidth,
          (pageHeight - 2 * margin) / imgHeight
      );
      const finalWidth = imgWidth * ratio;
      const finalHeight = imgHeight * ratio;

      const x = (pageWidth - finalWidth) / 2;
      const y = (pageHeight - finalHeight) / 2;

      doc.addImage(img, 'JPEG', x, y, finalWidth, finalHeight);
    });

    const fileName = `${projectInfo.value.projectName || '附件材料'}.pdf`;
    doc.save(fileName);

    ElMessage.success('PDF已在前端生成并下载');

  } catch (error) {
    console.error('生成PDF失败:', error);
    ElMessage.error(`生成PDF失败: ${error.message}`);
  } finally {
    loadingInstance.close();
  }
}

// 编辑封面
const handleEditCover = () => {
  console.log('打开封面编辑器，当前封面数据:', coverData.value)
  showCoverEditor.value = true
}

// 封面编辑确认
const handleCoverEditorConfirm = (data) => {
  console.log('--- pdf-preview-page: handleCoverEditorConfirm 开始 ---');
  console.log('接收到的封面数据 (来自 CoverEditor):', data);
  console.log('更新前 pdf-preview-page 中的 coverData:', JSON.parse(JSON.stringify(coverData.value)));

  // 直接使用从 CoverEditor 接收到的完整数据结构
  coverData.value = data;

  console.log('更新后 pdf-preview-page 中的 coverData:', JSON.parse(JSON.stringify(coverData.value)));

  nextTick(() => {
    console.log('DOM 更新周期后，当前封面数据:', JSON.parse(JSON.stringify(coverData.value)));
    console.log('--- pdf-preview-page: handleCoverEditorConfirm 结束 ---');
  });

  showCoverEditor.value = false;
  ElMessage.success('封面信息已更新');
}

// 封面编辑取消
const handleCoverEditorCancel = () => {
  console.log('取消封面编辑')
  showCoverEditor.value = false
}

// 返回上一步
const handleGoBack = () => {
  router.back()
}

// 组件挂载时初始化
onMounted(() => {
  initData()
  loadAllImages()
})
</script>

<style scoped>
.pdf-preview-page {
  height: 105vh;
  overflow: hidden;
}
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 105vh;
  background-color: #f5f5f5;
}
.loading-content {
  text-align: center;
}.loading-spinner {
   width: 48px;
   height: 48px;
   border: 4px solid #f3f3f3;
   border-top: 4px solid #00b96b;
   border-radius: 50%;
   animation: spin 1s linear infinite;
   margin: 0 auto 16px;
 }
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.loading-content p {
  color: #666;
  font-size: 16px;
  margin: 0;
}
</style>
